package ioc

import (
	"booksmart/book/config"
	"booksmart/book/internal/web"
	"booksmart/book/internal/web/middleware"
	logger2 "booksmart/book/pkg/ginx/middleware/logger"
	"booksmart/book/pkg/logger"
	"context"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

func InitGin(mdls []gin.HandlerFunc, hdl *web.UserHandler, articleHal *web.ArticleHandler) *gin.Engine {
	server := gin.Default()
	server.Use(mdls...)
	hdl.RegisterRoutes(server)
	articleHal.RegisterRoutes(server)
	return server
}

func InitMiddlewares(l logger.LoggerV1) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		cors.New(cors.Config{
			//AllowOrigins:     []string{"https://foo.com"},
			//AllowMethods:     []string{"PUT", "PATCH"},
			AllowHeaders: []string{"Origin", "Content-Type"},
			//ExposeHeaders:    []string{"Content-Length"},
			AllowCredentials: true,
			AllowOriginFunc: func(origin string) bool {
				if strings.Contains(origin, "localhost") {
					return true
				}
				return strings.Contains(origin, "sensetime.com")
			},
			MaxAge: 12 * time.Hour,
		}),
		logger2.NewMiddlewareBuilder(func(ctx context.Context, al *logger2.AccessLog) {
			l.Debug("HTTP请求", logger.Field{Name: "al", Value: al})
		}).SetAllowReqBody(true).SetAllowRespBody(true).Builder(),
		InitStoreHdl(),
		middleware.NewLoginMiddleware().SetPath("/users/login").SetPath("/users/singUp").Build(),
	}
}

func InitStoreHdl() gin.HandlerFunc {
	newStore, err := redis.NewStore(16, "tcp", config.Config.Redis.Addr, "",
		[]byte("secret"))
	if err != nil {
		panic(err)
	}
	return sessions.Sessions("mysession", newStore)
}
